package com.maozzi.service.acl.domain.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maozzi.common.util.ParamCheckUtil;
import com.maozzi.service.acl.domain.UserRoleDomainService;
import com.maozzi.service.acl.repository.mapper.UserRoleMapper;
import com.maozzi.service.acl.repository.model.UserRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 权限 - 用户角色 domain service
 *
 * @author maozi
 */
@Service
public class UserRoleDomainServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleDomainService {

    @Override
    public List<UserRole> getUserRole(Long userId) {
        LambdaQueryWrapper<UserRole> query = Wrappers.lambdaQuery(UserRole.class)
                .eq(UserRole::getUserId, userId);

        return this.list(query);
    }

    @Override
    public Boolean delUserRoleBatch(Long userId) {
        LambdaQueryWrapper<UserRole> query = Wrappers.lambdaQuery(UserRole.class)
                .eq(UserRole::getUserId, userId);

        return this.remove(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addUserRole(Long userId, Long... roleIds) {
        List<UserRole> list = new ArrayList<>();
        List<Long> roles = Arrays.stream(roleIds).distinct().toList();
        for (Long roleId : roles) {
            list.add(new UserRole().setUserId(userId).setRoleId(roleId));
        }

        this.saveBatch(list);

        return true;
    }

    @Override
    public Boolean using(Long roleId) {
        ParamCheckUtil.notNull(roleId, "角色ID为空");

        LambdaQueryWrapper<UserRole> query = Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getRoleId, roleId);

        return this.count(query) > 0;
    }
}
